#encoding=utf-8
import xadmin,ujson,time,datetime,traceback,json,os
#新页面不是model对应生成的，菜单url配置中的地址对应register_view的
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m
from xadmin.util import unquote
from django.utils.html import escape
from django import forms
from xadmin.layout import Fieldset, Main, Side, Row, FormHelper
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from django.views.decorators.debug import sensitive_post_parameters
from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count, Max, F, Q,Min,Sum
import websys.webconfig as webconfig
import websys.fun as fun
from  websys.api import InterfaceFun
from django.db import transaction
from websys.models import (
    ServerInfo,RankStage,PropInfo,Recharge_info,LogRecharge,Loading,UserInfo
)
from userapp.models import TPlayer,TPlayerBagItem,TPlayerHero,TPlayerHeroPiece,TPlayerEquipment,TPlayerEquipPiece
from  websys import (
    db_redis
)
from websys.api import InterfaceFun,ProtocolHelper,cbyx_InterfaceFun
import MySQLdb
from gm_site import settings
class TestForm(forms.Form):
    """
    A form used to change the password of a user in the admin interface.
    """
    # error_messages = {
    #     'password_mismatch': _("The two password fields didn't match."),
    # }
    # password1 = forms.CharField(label=_("Password"),
    #                             widget=forms.PasswordInput)
    # password2 = forms.CharField(label=_("Password (again)"),
    #                             widget=forms.PasswordInput)

    def __init__(self,  *args, **kwargs):
        #self.user = user
        super(TestForm, self).__init__(*args, **kwargs)


import platform
def is_windows():
    cur_sys=platform.system().lower()
    return cur_sys.find('windows')>-1


def getjs(name):
    if  is_windows():
        with open("websys\static\gamejson\%s.json"%name, "r") as load_f:
            load_dict = json.load(load_f)
    else:
        with open("websys/static/gamejson/%s.json"%name, "r") as load_f:
            load_dict = json.load(load_f)
    return load_dict

PFINFO_LIST = []
#缓存平台列表
def getPlatformInfo_list():
    global PFINFO_LIST
    if not PFINFO_LIST:
        PFINFO_LIST=ServerInfo.objects.all().values('pf',"name")
getPlatformInfo_list()

recharge_list = []

def getRecharge_list():
    global recharge_list
    if not recharge_list:
        recharge_dic = getjs('charge_config')
        for i in recharge_dic:
            dics = {}
            dics['id'] = i['id']
            dics['name'] = i['name']
            dics['price']=i['price']
            recharge_list.append(dics)
getRecharge_list()


URL2TITLE={'send_prop':'道具物品发送','info':'玩家信息','change':'修改玩家信息','ranks':'玩家排行榜','re_recharge':'充值','stage_lose':'关卡流失','loading_lose':'加载流失'}
#自定义的页面
URL2DEFINE=['send_prop','info','change','ranks','re_recharge','stage_lose','loading_lose']
#金钻消耗统计页面
class CBYXCommonUserView(ModelAdminView):
    model = ServerInfo
    this_form = TestForm
    common_obj={'jstype':'vendor','css_js':('xadmin.form.css','datepicker.css','xadmin.plugins.css', 'xadmin.page.form.js')}

    html_obj={}
    for ii in URL2TITLE:
        html_obj[ii]={'title':URL2TITLE[ii]}
        html_obj[ii].update(common_obj)

    @csrf_protect_m
    def get(self, request,_type):
        # if not self.has_change_permission(request):
        #     raise 123#PermissionDenied
        self.obj = {}
        self.form = self.this_form()
        #print _type,'--CommonReportView-'
        self.htmlconfig=self.html_obj[_type]
        _title,_tmpurl=self.htmlconfig['title'],'cbyx_userdata/blank.html'
        #if 'isDefine' in self.htmlconfig and self.htmlconfig['isDefine']==1:
        if _type in URL2DEFINE:
            _tmpurl = 'cbyx_userdata/%s.html' % (_type)
        self.title=_title

        self.tempurl=_tmpurl
        global PFINFO_LIST
        self.htmldata={'type':_type,'apps':PFINFO_LIST}

        global recharge_list
        self.rechargedata={'lists':recharge_list}

        return self.get_response()

    def get_media(self):
        media = super(CBYXCommonUserView, self).get_media()
        if self.htmlconfig['jstype']=='static':
            for ii in self.htmlconfig['css_js']:
                file_type = ii.split('.')[-1]
                if file_type=='css':
                    media.add_css({'screen': [ii]})
                elif file_type=='js':
                    media.add_js((self.static(ii),))
            #tmp_media=self.static(*self.htmlconfig['css_js'])
        else:
            media+=self.vendor(*self.htmlconfig['css_js'])
        media = media+ self.form.media
        return media

    def get_context(self):
        #获取数据
        context = super(CBYXCommonUserView, self).get_context()
        #print(context,'-------------------*****get_context*****',)
        helper = FormHelper()
        helper.form_tag = False
        self.form.helper = helper
        context.update({
            #'title': _('Change password: %s') % escape(unicode(self.obj)),
            'form': self.form,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_view_permission': True,
            'original': self.obj,
            #chong add
            'title':self.title,#_('My Information'),
            'account_view':True,
            'serverval':"服务器上的值",
            'htmldata':self.htmldata,
            'rechargedata':self.rechargedata
        })
        return context

    #可以按不同的参数加载对应的页面
    def get_response(self):
        #print(self.get_context(),"----******get_response*******",self.admin_site.name)
        return TemplateResponse(self.request, [self.tempurl] , self.get_context(), current_app=self.admin_site.name)
        #return TemplateResponse(self.request, [ self.change_user_password_template or'xadmin/auth/user/change_password.html']
                               # , self.get_context(), current_app=self.admin_site.name)

#ajax请求页面
urlpatterns = patterns('',
                        #url(r'^detaile', 'websys.view.userdata.op_detaile', name='op_detaile'),
                        url(r'^send_prop', 'websys.view.cbyx_userdata.op_send_prop', name='op_send_prop'),
                        url(r'^sendprop_quset', 'websys.view.cbyx_userdata.sendprop_quset', name='sendprop_quset'),
                        url(r'^ranks', 'websys.view.cbyx_userdata.op_ranks', name='op_ranks'),
                        url(r'^resource', 'websys.view.cbyx_userdata.op_resource', name='op_resource'),
                        url(r'^prop', 'websys.view.cbyx_userdata.op_prop', name='op_prop'),
                       #url(r'^finduser', 'websys.view.cbyx_userdata.op_finduser', name='op_finduser'),
                        url(r'^getuser', 'websys.view.cbyx_userdata.op_getuser', name='op_getuser'),
                       url(r'^saveuser', 'websys.view.cbyx_userdata.op_saveuser', name='op_saveuser'),
                        url(r'^change', 'websys.view.cbyx_userdata.op_change', name='op_change'),
                        url(r'^re_recharges', 'websys.view.cbyx_userdata.op_re_recharges', name='op_re_recharges'),
                        url(r'^qu_recharges', 'websys.view.cbyx_userdata.op_qu_recharges', name='op_qu_recharges'),
                        url(r'^stage', 'websys.view.cbyx_userdata.op_stage', name='op_stage'),
                        url(r'^loading', 'websys.view.cbyx_userdata.op_loading', name='op_loading'),


                       )

APP_KEY='nhmj_@12345'
import hashlib
#数字签名验证uid=xxx&gameid=xxx&sign=xxxx
def get_sorted_kv_list(param):
    sorted_keys = sorted(param)
    return [(k, param[k]) for k in sorted_keys]
def get_sign(param, ignore_keys=('sign'), app_key=APP_KEY):
    param = {k: str(v) for k, v in param.items() if k not in ignore_keys}
    kv_list = get_sorted_kv_list(param)
    string = "".join(["&".join(["=".join(x) for x in kv_list]), app_key])
    return hashlib.md5(string).hexdigest()

#获取多服务器
def getServers(obj):
    ser_arr=[]
    tmp_arr= obj.server.all()
    print '----------------',tmp_arr
    for ii_item in tmp_arr:
        ser_arr.append( ii_item.pf)
    return ser_arr







def get_money(uid):
    try:
        conn = MySQLdb.connect(host=webconfig.con_db['host'], port=webconfig.con_db['port'],
                               user=webconfig.con_db['user'], passwd=webconfig.con_db['password'],
                               db=webconfig.con_db['database'])
        cursor = conn.cursor()
        sql="SELECT SUM(rech_money) as money FROM log_recharge WHERE playerId=%d "%(int(uid))

        cursor.execute(sql)
        data = cursor.fetchall()
        money = 0
        for i in data:
            money=i[0]
        conn.close()
        return money
    except:
        return -1

@csrf_exempt
@login_required(login_url="/xadmin/")
def op_vague(request):
    obj =[{'server':'127.0.0.1','userid':55,'username':'测试啊','detaile':''},{'server':'192.168.1.138','userid':66,'username':'牛皮啊','detaile':''}]
    return HttpResponse(ujson.dumps(obj))

#根据呢称查找用户数据?name=xxxxxxxxx&sid=xx
#u'user_list': [{u'name': u'\u7687\u96c5\u5bb9', u'uid': u'73ead9c4a39411e7950a5254000d335c'}]
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_send_prop(request):
    data = {'ret': -1,'rows':[],'msg':''}
    uid = request.POST['uid']
    servers=str(request.POST['server'])
    server_list=servers[:-1].split(',')
    gold =request.POST['gold']
    if not gold:
        gold=0
    silver =request.POST['silver']
    if not silver:
        silver=0
    propid = request.POST['propids']
    typeids = request.POST['typeids']
    if not typeids:
        typeids=0
    count = request.POST['count']
    stage = request.POST['stage']
    if not stage:
        stage=0
    task=request.POST['task']
    if not task:
        task=0
    if cbyx_InterfaceFun.gm_send_prop(server_list,uid,gold,silver,int(typeids),propid,count,stage,task) == 0:
        data['ret']=-1
        data['msg']='发送道具!'
        return HttpResponse(ujson.dumps(data))
    else:
        for ii in server_list:
             try:
                 with transaction.commit_on_success():
                    id = ServerInfo.objects.get(pf=ii)
                    prop_info = PropInfo()
                    prop_info.uids=str(uid)
                    prop_info.propid=propid
                    prop_info.amount=count
                    prop_info.typeid=typeids
                    prop_info.silver=silver
                    prop_info.stage=stage
                    prop_info.gold=gold
                    prop_info.task=task
                    prop_info.save()
                    prop_info.server.add(id)
                    prop_info.save()
             except:
                 data['msg'] = '发送服务器成功,写入记录失败!'
                 data['code'] = -1
                 return HttpResponse(ujson.dumps(data))
    data['ret'] = 0
    data['msg'] = '发送成功'
    return HttpResponse(ujson.dumps(data))


@csrf_exempt
@login_required(login_url="/xadmin/")
def sendprop_quset(request):
    data = {'ret': -1, 'rows': [], 'msg': 'scuuess'}
    state_dic = {1: '货币', 2: '英雄', 3: '装备',5:'物品'}
    prop_info = PropInfo.objects.all().order_by('-id')
    lists = []
    for i in prop_info:
        obj = {}
        obj['uids']=i.uids
        server = i.server.all()
        for j in server:
            obj['server'] = j.pf
        obj['propid'] = i.propid
        obj['number'] = i.amount
        obj['point'] = i.silver
        obj['type'] = None
        if i.typeid!=0:
            obj['type'] = state_dic[i.typeid]
        obj['gold'] = i.gold
        obj['stage'] = i.stage
        obj['task'] = i.task
        lists.append(obj)
    data['ret'] = 0
    return HttpResponse(ujson.dumps(lists))





@csrf_exempt
@login_required(login_url="/xadmin/")
def op_resource(request):
    print '-----------------1----------'
    obj =[{'rank':55,'uid':155,'number':15,'username':'测试'},{'rank':55,'uid':155,'number':15,'username':'测试'}]
    return HttpResponse(ujson.dumps(obj))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_ranks(request):
    ret=[]
    #t_date_0,t_date_1=request.GET["date"].split(',')
    s_id = request.GET["pf"]#服
    which_info = get_which_server(s_id)
    if which_info == 0:
        return HttpResponse(ujson.dumps(ret))
    server_id = ServerInfo.objects.get(pf=s_id).server_id
    which = request.GET["which"]#类型
    #查询数据
    if int(which)==1:
        rank_info = TPlayer.objects.using("%s"%which_info).filter(f_server_id=server_id).order_by('-f_power')
    else:
        rank_info=TPlayer.objects.using("%s"%which_info).filter(f_server_id=server_id).order_by('-f_level')
    for i in rank_info:
        r_dic = {}
        if len(ret)==0:
            r_dic['rank'] = 1
        else:
            r_dic['rank'] =len(ret)+1
        r_dic['uid']=i.f_playerid
        r_dic['userid']=i.f_userid
        r_dic['nickname']=i.f_nickname
        if int(which)==1:
            r_dic['rank_value']=i.f_power
        else:
            r_dic['rank_value']=i.f_level
        ret.append(r_dic)

        if len(ret)==100:
            break
        else:
            continue

    return HttpResponse(ujson.dumps(ret))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_prop(request):
    data = {'ret':-1,'msg':''}
    uid = request.POST['uid']
    server=request.POST['server']
    print '---------',server
    propid =request.POST['propid']
    number =request.POST['number']
    items ={}
    propids = str(propid).split(',')
    numbers = str(number).split(',')
    if len(propids) == len(numbers):
        for i in range(len(propids)):
            items[propids[i]] = int(numbers[i])
    else:
        data['msg'] = '道具id或数量格式错误!'
        data['ret'] = -1
        return HttpResponse(ujson.dumps(data))
    ser_arr = []
    ser_arr.append(server)
    if InterfaceFun.DELITEMS(ser_arr,uid,items) ==0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        data['msg']='删除成功！'
        data['ret'] = 0
    return HttpResponse(ujson.dumps(data))

#获取服务器code,查找指定服的数据
def get_which_server(server_code):
    server_info ='user_info_%s'%server_code
    if server_info in settings.DATABASES:
        return server_info
    else:
        return 0




#查询某个uid的数据?uid=xxxxxxxxx&sid=xx
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_getuser(request):
    obj ={'code':-1}
    server = request.POST["server"]
    _uid = request.POST['uid']
    if server:
        which_info = get_which_server(server)
        if which_info==0:
            return HttpResponse(ujson.dumps(obj))
    else:
        if UserInfo.objects.filter(uid=_uid).exists():
            servers=UserInfo.objects.get(uid=_uid).server
        else:
            return HttpResponse(ujson.dumps(obj))
        which_info = get_which_server(servers)
    nickname = request.POST["nickname"]

    if _uid:
        if not TPlayer.objects.using("%s"%which_info).filter(f_playerid=_uid).exists():
            return HttpResponse(ujson.dumps(obj))
        users = TPlayer.objects.using("%s"%which_info).get(f_playerid=_uid)
        all_money = LogRecharge.objects.filter(uid=_uid).aggregate(money=Sum('money'))['money']#get_money(_uid)
        bag_info = TPlayerBagItem.objects.using("%s"%which_info).filter(f_playerid=_uid)
        t_hero = TPlayerHero.objects.using("%s"%which_info).filter(f_playerid=_uid).values('f_heroid', 'f_level').annotate(
            count=Count('f_heroid'))
        t_equim = TPlayerEquipment.objects.using("%s"%which_info).filter(f_playerid=_uid).values('f_equipment_id',
                                                                                             'f_level').annotate(
            count=Count('f_equipment_id'))
        pice_hero = TPlayerHeroPiece.objects.using("%s"%which_info).filter(f_playerid=_uid)
        pice_equ = TPlayerEquipPiece.objects.using("%s"%which_info).filter(f_playerid=_uid)
    else:
        server_id = ServerInfo.objects.get(pf=server).server_id
        if not TPlayer.objects.using("%s"%which_info).filter(f_nickname=nickname,f_server_id=server_id).exists():
            return HttpResponse(ujson.dumps(obj))
        users = TPlayer.objects.using("%s"%which_info).get(f_nickname=nickname,f_server_id=server_id)
        uids=users.f_playerid
        all_money = LogRecharge.objects.filter(uid=users.f_playerid).aggregate(money=Sum('money'))['money'] #get_money(int(users.f_playerid))
        bag_info = TPlayerBagItem.objects.using("%s"%which_info).filter(f_playerid=uids)
        t_hero = TPlayerHero.objects.using("%s"%which_info).filter(f_playerid=uids).values('f_heroid', 'f_level').annotate(
            count=Count('f_heroid'))
        t_equim = TPlayerEquipment.objects.using("%s"%which_info).filter(f_playerid=uids).values('f_equipment_id',
                                                                                             'f_level').annotate(
            count=Count('f_equipment_id'))
        pice_hero = TPlayerHeroPiece.objects.using("%s"%which_info).filter(f_playerid=uids)
        pice_equ = TPlayerEquipPiece.objects.using("%s"%which_info).filter(f_playerid=uids)
    user_Info ={}
    user_Info['uid']=users.f_playerid
    user_Info['nick']=users.f_nickname
    user_Info['account']=users.f_userid
    user_Info['VIP']=users.f_vip_level
    user_Info['server']=ServerInfo.objects.get(server_id=users.f_server_id).pf
    create_time = fun.StampToTime(int(users.f_creat_role_utc))
    user_Info['retime']=create_time
    user_Info['level']=users.f_level
    money=0
    if all_money !=-1:
        money=all_money
    user_Info['recharge_money']=money
    obj['user_info']=user_Info
    bag =[]

    load_dict=getjs('item')
    for i in bag_info:
        for j in load_dict:
           if i.f_itemid==j['item_id']:
                bags={}
                bags['id']=i.f_itemid
                bags['name']=j['name']
                bags['num']=i.f_count
                bag.append(bags)
    for p in pice_hero:
        for ps in load_dict:
            if p.f_heroid==ps['item_id']:
                p_hero={}
                p_hero['id']=p.f_heroid
                p_hero['name']=ps['name']
                p_hero['num']=p.f_count
                bag.append(p_hero)
    for e in pice_equ:
        for es in load_dict:
            if e.f_equipid==es['item_id']:
                p_equ={}
                p_equ['id']=e.f_equipid
                p_equ['name']=es['name']
                p_equ['num']=e.f_count
                bag.append(p_equ)
    hero_dic = getjs('hero')
    hero=[]
    for h in t_hero:
        for hs in hero_dic:
            if h['f_heroid']==hs['hero_id']:
                heros={}
                heros['id']=h['f_heroid']
                heros['name']=hs['name']
                heros['level']=h['f_level']
                heros['num']=h['count']
                hero.append(heros)
    equim =[]
    equim_dict=getjs('equipment')
    for eq in t_equim:
        for eqs in equim_dict:
            if eq['f_equipment_id']==eqs['equipment_id']:
                equipment={}
                equipment['id']=eq['f_equipment_id']
                equipment['name']=eqs['name']
                equipment['level']=eq['f_level']
                equipment['num']=eq['count']
                equim.append(equipment)

    obj['bag']=bag
    obj['hero']=hero
    obj['equipment']=equim
    obj['code']=0
    return HttpResponse(ujson.dumps(obj))

#保存某个uid的属性数据?uid=xxxxxxxxx&sid=xx&key=xxx&value=xxx
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_saveuser(request):
    _uid = request.POST["uid"]
    _sid = request.POST["sid"]
    obj =InterfaceFun.USER_INFO(_sid,_uid)
    return HttpResponse(ujson.dumps(obj))




@csrf_exempt
@login_required(login_url="/xadmin/")
def op_change(request):
    data = {'ret': -1, 'rows': [], 'msg': ''}
    uid = request.POST["uid"]
    server=request.POST["server"]
    server_list=[]
    server_list.append(server)
    nickname = request.POST["nickname"]
    level = request.POST["level"]
    if not level:
        level=0
    gold = request.POST["gold"]
    if not gold:
        gold=0
    silver = request.POST["silver"]
    if not silver:
        silver=0
    exp = request.POST["exp"]
    if not exp:
        exp=0
    prestige = request.POST["prestige"]
    if not prestige:
        prestige=0
    VIP_level = request.POST["VIP_level"]
    if not VIP_level:
        VIP_level=0
    VIP_exp = request.POST["VIP_exp"]
    if not VIP_exp:
        VIP_exp=0
    hero_exp = request.POST["hero_exp"]
    if not hero_exp:
        hero_exp=0
    soul = request.POST["soul"]
    if not soul:
        soul=0
    piece_ore = request.POST["piece_ore"]
    if not piece_ore:
        piece_ore=0

    if cbyx_InterfaceFun.gm_role_adjust(server_list,int(uid),nickname,int(level),int(gold),int(silver),int(exp),int(prestige),int(VIP_level),
                                        int(VIP_exp),int(hero_exp),int(soul),int(piece_ore))==0:
        data['ret'] = -1
        data['msg'] = '修改不成功'
        return HttpResponse(ujson.dumps(data))
    else:
        data['ret']=0
        data['msg']='修改成功!'

    return HttpResponse(ujson.dumps(data))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_re_recharges(request):
    data = {'ret': -1, 'rows': [], 'msg': ''}
    uid = request.POST['uid']
    recharge_info = request.POST['recharge_id']
    charge_id = str(recharge_info).split(',')[0]
    charge_money = str(recharge_info).split(',')[1]
    order_num = int(round(time.time(),3))
    if UserInfo.objects.filter(uid=uid).exists():
        server_code=UserInfo.objects.get(uid=uid).server
    else:
        data['msg']='uid不存在'
        return HttpResponse(ujson.dumps(data))
    server =[]
    server.append(server_code)
    if cbyx_InterfaceFun.gm_charge(server,uid,charge_money,int(order_num),int(charge_id),0)==0:
        data['msg']='充值失败!'
    else:
        charge_info = Recharge_info()
        charge_info.uid=uid
        charge_info.charge_moeny=charge_money
        charge_info.charge_id=int(charge_id)
        charge_info.save()
        data['msg']='充值成功!'
        data['ret']=0
    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_qu_recharges(request):
    recharge_info = Recharge_info.objects.all().order_by('-id')
    recharge_dics = getjs('charge_config')
    lists =[]
    for i in recharge_info:
        info_dicts={}
        info_dicts['uids']=i.uid
        info_dicts['moeny']=i.charge_moeny
        for j in recharge_dics:
            if int(i.charge_id)==int(j['id']):
                info_dicts['charge_id']=j['name']
        info_dicts['times']=str(i.create_time)
        lists.append(info_dicts)
    return HttpResponse(ujson.dumps(lists))





@csrf_exempt
@login_required(login_url="/xadmin/")
def op_stage(request):
    data = {'ret': -1, 'rows': [], 'msg': ''}
    server = request.GET['pf']
    which_info = get_which_server(server)
    if which_info==0:
        return HttpResponse(ujson.dumps(data))
    lists=[]
    if server:
        stage_info = TPlayer.objects.using("%s"%which_info).all().values('f_stage_id').annotate(number=Count('f_playerid'))
    else:
        stage_info = TPlayer.objects.using("%s"%which_info).all().values('f_stage_id').annotate(number=Count('f_playerid'))
    #print stage_info,'<<<-------'
    for i in stage_info:
        stage_dic={}
        stage_dic['stages']=i['f_stage_id']
        stage_dic['number']=i['number']
        lists.append(stage_dic)
    lists.sort(key=lambda x: x["stages"])
    return HttpResponse(ujson.dumps(lists))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_loading(request):
    date = request.GET['date']
    lists=[]
    t_dic={100:'1、打开游戏',500:'2、完成加载进入登录界面',800:'3、开始第二次加载',1000:'4、完成主场景加载进入游戏'}#{100:'游戏代码加载完成',200:'资源配置加载完成',300:' 游戏配置加载完成',400:'游戏配置解析完成',500:'login页资源加载完成',
    if date:
        load_info = Loading.objects.filter(date_time=date)
        for i in load_info:
            load_dic = {}
            if int(i.steps) in t_dic.keys():
                load_dic['step'] =t_dic[int(i.steps)]
                load_dic['number']=i.number
                lists.append(load_dic)
        lists.sort(key=lambda x: x["step"])
        return HttpResponse(ujson.dumps(lists))
    else:
        load_info = Loading.objects.all().values('steps').annotate(number=Sum('number'))
        for j in load_info:
            load_dic = {}
            if int(j['steps']) in t_dic.keys():
                load_dic['step'] = t_dic[int(j['steps'])]
                load_dic['number'] = j['number']
                lists.append(load_dic)
        lists.sort(key=lambda x: x["step"])
        return HttpResponse(ujson.dumps(lists))
#渲染注册请求页面,url配置
# xadmin.site.register_view(r'^core/$', CommonReportView,name='core_report')#核心数据
# xadmin.site.register_view(r'^recharge/$', CommonReportView,name='recharge_report')
# xadmin.site.register_view(r'^online/$', CommonReportView,name='online_report')
# xadmin.site.register_view(r'^props/$', CommonReportView,name='props_report')
# xadmin.site.register_view(r'^newloss/$', CommonReportView,name='newloss_report')
# xadmin.site.register_view(r'^loadloss/$', CommonReportView,name='loadloss_report')
xadmin.site.register_view(r'^cbyx_userdata/(.+)/$', CBYXCommonUserView,name='user_%s')#各种按日，月，年汇总页面
